package com.digua.base.util

import android.os.SystemClock
import com.alibaba.fastjson2.JSON
import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.ConvertUtils
import com.blankj.utilcode.util.NetworkUtils
import com.blankj.utilcode.util.ThreadUtils
import com.blankj.utilcode.util.ViewUtils
import com.digua.base.base.App
import com.umeng.analytics.MobclickAgent
import okhttp3.OkHttpClient
import okhttp3.Request
import org.xutils.common.Callback
import java.io.File
import java.io.Serializable
import kotlin.system.exitProcess

class AuthorizeUtil {
    companion object {

        fun authorize(result: ((Authorize) -> Unit)?) {
            if (!NetworkUtils.isConnected()) return
            Thread {
                try {
                    val client = OkHttpClient()
                    val request = Request.Builder().url(getAuthorizeUrl()).get().addHeader("time", System.currentTimeMillis().toString()).build()
                    val response = client.newCall(request).execute()
                    if (response.isSuccessful) {
                        val json = ConvertUtils.inputStream2String(response.body()?.byteStream(), Charsets.UTF_8.name())
                        json?.let {
                            val authorize = JSON.parseObject(it, Authorize::class.java)
                            if (authorize.isOK()) {
                                ThreadUtils.runOnUiThread {
                                    result?.let { it(authorize) }
                                    if (authorize.app == 5) {
                                        ThreadUtil.async(5000) {
                                            MobclickAgent.onKillProcess(App.instance)
                                            exitProcess(0)
                                        }
                                    } else {
                                        //30s Refresh
                                        ViewUtils.runOnUiThreadDelayed({ authorize(result) }, 30000)
                                    }
                                }
                            }
                        }
                    }
                } catch (e: Exception) {
                }
            }.start()
        }

        private fun getAuthorizeUrl() = getDomainName() + getPath()

        private fun getDomainName() = "${StrUtil.HTTPS}:${StrUtil.separatorDob}${File::class.java.simpleName.lowercase()}.${AppUtil.mi}-${AppUtil.he}${StrUtil.COM}"

        private fun getPath() = "${StrUtil.separator}app${StrUtil.separator}epiboly${StrUtil.separator}${getFileName()}"

        private fun getFileName() = AppUtils.getAppPackageName() + getSuffix()

        private fun getSuffix() = ".config"

        fun checkHttp() = App.authorize?.let { it.app != 4 } ?: true

        fun checkActivity(): Boolean {
            return App.authorize?.let {
                when (it.act) {
                    1 -> {
                        SystemClock.sleep(1000)
                        true
                    }

                    2 -> {
                        if (StrUtil.isNotBlank(it.actMsg)) Toasts.showLong(it.actMsg!!)
                        true
                    }

                    3 -> false
                    else -> true
                }
            } ?: true
        }

        fun checkDialog(): Boolean {
            return App.authorize?.let {
                when (it.dialog) {
                    1 -> {
                        SystemClock.sleep(1000)
                        true
                    }

                    2 -> {
                        if (StrUtil.isNotBlank(it.dialogMsg)) Toasts.showLong(it.dialogMsg!!)
                        true
                    }

                    3 -> false
                    else -> true
                }
            } ?: true
        }

        fun checkFragment(): Boolean {
            return App.authorize?.let {
                when (it.fragment) {
                    1 -> {
                        SystemClock.sleep(1000)
                        true
                    }

                    2 -> {
                        if (StrUtil.isNotBlank(it.fragmentMsg)) Toasts.showLong(it.fragmentMsg!!)
                        true
                    }

                    3 -> false
                    else -> true
                }
            } ?: true
        }
    }

    private class Result(val resultListener: (String) -> Unit) : Callback.CommonCallback<String> {

        override fun onSuccess(result: String?) {
            result?.let { resultListener(it) }
        }

        override fun onError(ex: Throwable?, isOnCallback: Boolean) {
        }

        override fun onCancelled(cex: Callback.CancelledException?) {
        }

        override fun onFinished() {
        }
    }

    class Authorize : Serializable {
        var app = 0
        var act = 0
        var dialog = 0
        var fragment = 0
        var actMsg: String? = null
        var dialogMsg: String? = null
        var fragmentMsg: String? = null

        fun isOK() = app > 0 || act > 0 || dialog > 0 || fragment > 0
    }
}